// 获取商品id
function getID(){
        let url = location.href
        let params = url.substring(url.indexOf('?') + 1) //id=50
        let paramsArr = params.split('=') //['id','50']
        getData(paramsArr[1])
}
getID()


// 获取商品数据
async function getData(id) {
    let data = await myPromise({
        method: 'get',
        url: 'http://api.yuguoxy.com/api/shop/find',
        data: {
            id
        }
    })
    let { resultCode, resultInfo } = data
    if (resultCode == 1) {
        // console.log(resultInfo)
        let id = resultInfo.id
        let price = resultInfo.price
        let name = resultInfo.shop
        let num = 0
        let url = resultInfo.picture
        let state= false
        let singlePrice=(num*price).toFixed(2)
        let obj = {
            id,
            url,
            name,
            num,
            price,
            singlePrice,
            state
        }
        let productList = JSON.parse(localStorage.getItem('productList')) || []
        if (!productList.some(item => item.id == obj.id)) {
            productList.push(obj)
        }
        localStorage.setItem('productList',JSON.stringify(productList))
        getImg(resultInfo.list)
        productDetail(obj)
        let jsonStr = JSON.stringify(obj)
        localStorage.setItem('product', jsonStr)
    }
}


//获取商品图片,渲染页面
function getImg(data) {
    let imgArr = data.splice(0, 4)
    let str = `<div class="imgBox">
               <img src="${imgArr[0]}" alt="商品图">
               <div class="glass none"></div>
               </div>
               <ul class="imgList">`
    let strArr = imgArr.map(item => {
        return `<li><img src="${item}" alt=""></li>`
    })
    str += strArr.join('')
    str = str + ` </ul>
                <div class="magnifier none">
                <img src="${imgArr[0]}" alt="">
                </div>`
    // console.log(str)
    $('main>.concent>.left').html(str)
    glassEvent()
}

// 实现放大镜效果
function glassEvent() {
    //给图片所在盒子绑定移动事件
    //  获取glass的宽高
    let glassW = $('main>.concent>.left .imgBox .glass').width()
    let glassH = $('main>.concent>.left .imgBox .glass').height()
    // 获取glass所在盒子的宽高
    let imgBoxW = $('main>.concent>.left .imgBox').width()
    let imgBoxH = $('main>.concent>.left .imgBox').height()
    // 获取大盒子的宽高
    let magnifierW = $('main>.concent>.left .magnifier').width()
    let magnifierH = $('main>.concent>.left .magnifier').height()
    // 计算galss与其父盒子的宽高比
    let scaleW = glassW / imgBoxW
    let scaleH = glassH / imgBoxH
    // 计算移动距离比例
    let moveScale = glassW / magnifierW
    // 给大图设置尺寸
    $('main>.concent>.left .magnifier>img').width(magnifierW / scaleW)
    $('main>.concent>.left .magnifier>img').height(magnifierH / scaleH)
    // 绑定鼠标移动事件
    $('main>.concent>.left').on('mousemove', '.imgBox', function (e) {
        target = e.target || e.srcElement
        let x = e.offsetX - glassW / 2
        let y = e.offsetY - glassH / 2
        $('main>.concent>.left .imgBox .glass').removeClass('none').addClass('block')
        $('main>.concent>.left .magnifier').removeClass('none').addClass('block')
        if (x < 0) {
            x = 0
        }
        if (x > imgBoxW - glassW) {
            x = imgBoxW - glassW
        }
        if (y < 0) {
            y = 0
        }
        if (y > imgBoxH - glassH) {
            y = imgBoxH - glassH
        }
        $('main>.concent>.left .imgBox .glass').css({
            left: x, top: y
        })
        $('main>.concent>.left .magnifier>img').css({
            left: -x / moveScale, top: -y / moveScale
        })

    })
    $('main>.concent>.left').on('mouseout', '.imgBox', function (e) {
        target = e.target || e.srcElement
        $('main>.concent>.left .imgBox .glass').removeClass('block').addClass('none')
        $('main>.concent>.left .magnifier').removeClass('block').addClass('none')

    })

    // 绑定点击事件到li，替换图片地址
    $('main>.concent>.left .imgList').on('click', 'li', function (e) {
        target = e.target || e.srcElement
        $(this).addClass('border').siblings().removeClass('border')
        let url = $(target).prop('src')
        $('main>.concent>.left .magnifier>img').prop('src', url)
        $('main>.concent>.left .imgBox>img').prop('src', url)

    })

}

// 实现商品详情
function productDetail(product) {
    let obj = product || {}
    //   渲染页面
    let str = `  <div class="productName" index="${obj.id}">${obj.name} </div>
                  <div class="info">一套48，两套88</div>
                  <div class="productPrice">
                      <div class="price">京东价：<span>￥${obj.price}</span></div>
                      <div class="rebate">促&ensp;销：<span>满99减100</span></div>
                  </div>
                  <div class="cart"></div>`

    $('main>.concent>.right').html(str)
    getCart()
    productEvent()

}
// 绑定点击事件到商品详情页

// 渲染添加购物车
function getCart() {

    let obj = JSON.parse(localStorage.getItem('product')) || {}

    let str = ` <input type="text" name="num" value="${obj.num > 0 ? obj.num : 0}">
                <input type="submit" name="plus" value="+">
                <input type="submit" name="minus" value="-" ${obj.num > 0 ? '' : 'disabled'}>
                <a class="cart_href " href="#">加入购物车</a>`
    $('main>.concent>.right>.cart').html(str)
}
function productEvent() {
    $('main>.concent>.right').on('click', 'input[name="plus"]', function (e) {
        target = e.target || e.srcElement
        let obj = JSON.parse(localStorage.getItem('product'))
        obj.num++
        obj.singlePrice=(obj.num*obj.price).toFixed(2)
        localStorage.setItem('product', JSON.stringify(obj))
        getCart()
    })
    $('main>.concent>.right').on('click', 'input[name="minus"]', function (e) {
        target = e.target || e.srcElement
        let obj = JSON.parse(localStorage.getItem('product'))
        if (obj.num > 0) {
            obj.num--
            obj.singlePrice=(obj.num*obj.price).toFixed(2)
            localStorage.setItem('product', JSON.stringify(obj))
        } else {
            obj.num = 0
            obj.singlePrice=(obj.num*obj.price).toFixed(2)
            localStorage.setItem('product', JSON.stringify(obj))
        }
        // console.log(obj)
        getCart()
    })
    $('main>.concent>.right').on('click', '.cart_href', function (e) {
        target = e.target || e.srcElement
        e.preventDefault()
        let num = $('main>.concent>.right input[name="num"]').val()
        let obj = JSON.parse(localStorage.getItem('product'))
        let productList=JSON.parse(localStorage.getItem('productList'))
        productList.forEach(item => {
            if (item.id == obj.id) {
                if (item.num == 0) {
                    item.num = 1
                    item.singlePrice=(item.num*item.price).toFixed(2)
                } else {
                    item.num += num
                    item.singlePrice=(item.num*obj.price).toFixed(2)
                }
            }
        })

        localStorage.setItem('productList', JSON.stringify(productList))
        getCart()
        location.href="./cart.html"

    })


}











// 防抖
const debounce = (fn, timer) => {
    let timeObj = null
    return function () {
        clearTimeout(timeObj)
        timeObj = setTimeout(() => {
            fn.apply(this)
        }, timer)
    }
}